#include "thread_pool.hh"
#include <iostream>
#include <thread>

using std::cout;
using std::endl;
using std::thread;

Thread_pool::Thread_pool(size_t queueSize, size_t threadNum)
    : _queueSize(queueSize)
    , _taskQueue(queueSize)
    , _threadNum(threadNum)
    , _isExit(false){

}

Thread_pool::~Thread_pool(){

}

void Thread_pool::start(){
    for(size_t i = 0; i < _threadNum; ++i){
        _threads.push_back(thread(&Thread_pool::doTask, this));
    }
}

void Thread_pool::stop(){
    _isExit = true;
    _taskQueue.setExit(true);
    for(auto& elem : _threads){
        elem.join();
    }
}

void Thread_pool::addTask(Task &&task){
    if(task){
        _taskQueue.push(std::move(task));
    }
}

void Thread_pool::doTask(){
    while(!_isExit){
        Task task = getTask();
        if(task){
            task();
        }else{
            cout << "Thread pool is empty" << endl;
        }
    }
}

Thread_pool::Task Thread_pool::getTask(){
    return _taskQueue.pop();
}